package com.zhanghaijun.createCode.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;

import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.junit.Assert;
import org.junit.Test;


/**
 * Created by zhanghaijun on 15/7/22.
 */
public class ShiroLoginOrLogoutTest {

    @Test
    public void testHelloWorld(){
        //1.获取SecurityManager工厂，此处使用Ini配置文件初始化 SecurityManager
        Factory<SecurityManager> factory =
                new IniSecurityManagerFactory("classpath:shiro/shiro.ini");

        //2.获取SecurityManager实例 并绑定给SecurityUtils
        SecurityManager securityManager = factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);
        //3.得到Subject 以及创建用户名/密码身份验证的Token(即用户身份/凭证)
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken("zhang","123");
        try{
            //4.登录
            subject.login(token);
        }catch (AuthenticationException e){
            e.printStackTrace();//认证失败
        }

        //5.断言用户是否以及登录成功
        Assert.assertEquals(true,subject.isAuthenticated());
        //6.登出
        subject.logout();
    }


    @Test
    public void testHelloWorld2(){
        //1.获取SecurityManager工厂，此处使用Ini配置文件初始化 SecurityManager
        Factory<SecurityManager> factory =
                new IniSecurityManagerFactory("classpath:shiro/shiro-realm.ini");

        //2.获取SecurityManager实例 并绑定给SecurityUtils
        SecurityManager securityManager = factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);
        //3.得到Subject 以及创建用户名/密码身份验证的Token(即用户身份/凭证)
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken("zhang","123");
        try{
            //4.登录
            subject.login(token);
        }catch (AuthenticationException e){
            e.printStackTrace();//认证失败
        }

        //5.断言用户是否以及登录成功
        Assert.assertEquals(true,subject.isAuthenticated());
        //6.登出
        subject.logout();
    }




}
